(in-package #:org.shirakumo.fraf.trial)

(defmethod load-image ((stream stream) (type (eql :sf3)) &key)
  (let ((image (org.shirakumo.sf3:read-sf3 stream)))
    (check-type image org.shirakumo.sf3:image)
    (flip-image-vertically
     (org.shirakumo.sf3:pixels image)
     (org.shirakumo.sf3:width image)
     (org.shirakumo.sf3:height image)
     (ldb (byte 4 0) (org.shirakumo.sf3:channels image)))
    (make-image-source (org.shirakumo.sf3:pixels image)
                       (org.shirakumo.sf3:width image)
                       (org.shirakumo.sf3:height image)
                       (ecase (org.shirakumo.sf3:pixel-format image)
                         (:uint8 :unsigned-byte)
                         (:uint16 :unsigned-short)
                         (:uint32 :unsigned-int)
                         (:sint8 :byte)
                         (:sint16 :short)
                         (:sint32 :int)
                         (:float16 :half-float)
                         (:float32 :float))
                       (ecase (org.shirakumo.sf3:channels image)
                         (#x01 :red)
                         (#x02 :rg)
                         (#x03 :rgb)
                         (#x04 :rgba)
                         (#x13 :bgr)
                         (#x34 :bgra)))))

(defmethod save-image ((source texture-source) (stream stream) (type (eql :sf3)) &key)
  (destructuring-bind (x y z w h d) (texture-source-src source)
    (declare (ignore x y z))
    (let ((image (org.shirakumo.sf3:make-image
                  (pixel-data source) w h :depth (or d 1) :pixel-type
                  (ecase (pixel-format source)
                    (:red :v)
                    (:rg :va)
                    (:rgb :rgb)
                    (:rgba :rgba)))))
      (org.shirakumo.sf3:write-sf3 image stream))))

(define-native-image-transcoder :sf3)
